import cv2
import numpy as np


# 全局变量来存储图像状态
current_image = None
def caidan():
    print('*********************************************************************************')
    print('*                               图像处理工具箱                                     *')
    print('*********************************************************************************')
    print('*                             0  = 退出                                         *')
    print('*                             1 = 导入图像                                       *')
    print('*                             2 = 查看功能菜单                                    *')
    print('*                             3 = 查看图像                                       *')
    print('*                             4 = 畸变纠正                                       *')
    print('*                             5 = 图像旋转                                       *')
    print('*                             6 = 对比度增强                                     *')
    print('*                             7 = 亮度增强                                       *')
    print('*                             8 = 水印添加                                       *')
    print('*                             9 = ROI                                          *')
    print('*                             10 = 图像缩放                                      *')
    print('*                             11 = 图像保存                                     *')
    print('*                             12 = 批量处理                                      *')
    print('*********************************************************************************')
    print('*                           Copyright（c）2025.11.17 By MZQ                      *')
    print('*********************************************************************************')
def read():
    """导入图像"""
    global current_image
    print('请输入需要处理的图像的路径：(路径不包含引号)')
    s=input()
    current_image=cv2.imread(s)
    if current_image is None:
        print('错误：无法读取图像，请检查路径是否正确')
        return None
    else:
        print(f'图像导入成功! 尺寸：({current_image.shape})')
        return True

def display(window_name="Image Preview", image=None):
    """查看图片"""
    global current_image
    if image is None:
        image = current_image

    cv2.imshow(window_name, image)
    cv2.waitKey(0)


def correct():
    """畸变纠正"""
    global current_image
    print('请依次点击图像的4个角点（点击顺序为：左上、右上、左下、右下）')
    print('点击完成后空格确认')
    points = []# 存储用户选择的4个点
    image_copy = current_image.copy()

    def pick_points(event, x, y, flags, param):
        # 鼠标回调函数，记录点击位置
        nonlocal points, image_copy
        if event == cv2.EVENT_LBUTTONDOWN and len(points) < 4:
            points.append((x, y))
            cv2.circle(image_copy, (x, y), 5, (255, 255, 0), -1)
            cv2.imshow('image_copy', image_copy)

    cv2.imshow('image_copy', image_copy)
    cv2.setMouseCallback('image_copy', pick_points)

    while True:
        key = cv2.waitKey(1) & 0xFF
        if key == ord(' ') and len(points) == 4:
            break

    cv2.destroyWindow('image_copy')

    if len(points) == 4:
        h, w = current_image.shape[:2]
        points_array = np.float32(points)
        points_image = [
            [0, 0],
            [w, 0],
            [0, h],
            [w, h]
        ]
        points_array2 = np.float32(points_image)
        M = cv2.getPerspectiveTransform(points_array, points_array2)

        # 直接更新全局变量
        current_image = cv2.warpPerspective(current_image, M, (w, h), cv2.INTER_LINEAR)
        print("畸变纠正完成")
        return True
    else:
        print("需要选择4个点")
        return False


def rotation():
    """图像旋转"""
    global current_image


    angle = float(input("请输入旋转角度（正数逆时针，负数顺时针）: "))


    h, w = current_image.shape[:2]
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    # 计算新图像尺寸
    cos_val = np.abs(M[0, 0])
    sin_val = np.abs(M[0, 1])
    new_w = int((h * sin_val) + (w * cos_val))
    new_h = int((h * cos_val) + (w * sin_val))
    # 调整旋转中心
    M[0, 2] += (new_w / 2) - center[0]
    M[1, 2] += (new_h / 2) - center[1]

    # 直接更新全局变量
    current_image = cv2.warpAffine(current_image, M, (new_w, new_h))
    print(f"图像旋转 {angle}° 完成")
    return True
def adjust_contrast():
    """对比度增强"""
    global current_image
    contrast = float(input("请输入对比度系数 (0.5-3.0, 1.0为原图): "))
    current_image = cv2.convertScaleAbs(
        current_image,
        alpha=contrast,
        beta=0
    )
    print(f"对比度增强完成 (系数: {contrast:.2f})")
    return True
def adjust_brightness():
    """亮度增强"""
    global current_image
    brightness = int(input("请输入亮度值 (-100到100, 0为原图): "))
    current_image = cv2.convertScaleAbs(
        current_image,
        alpha=1.0,
        beta=brightness
    )
    print(f"亮度增强完成 (值: {brightness})")
    return True
def add_watermark():
    """添加水印"""
    global current_image
    text = input("请输入水印文本: ")

    print("选择水印位置:\n1 - 左上角\n2 - 右上角\n3 - 左下角\n4 - 右下角\n5 - 中心")


    choice = int(input("请选择位置 (1-5): "))
    h, w = current_image.shape[:2]

    positions = {
        1: (50, 50),
        2: (w - 200, 50),
        3: (50, h - 50),
        4: (w - 200, h - 50),
        5: (w // 2 - 100, h // 2)
        }

    position = positions.get(choice, (w - 200, h - 50))

        # 添加水印
    cv2.putText(current_image,
                text,
                position,
                cv2.FONT_HERSHEY_SIMPLEX,
                1,
                (255,0 ,0 ),
                2,
                cv2.LINE_AA
                )
    print("水印添加完成")
    return True

def resize():
    """图像缩放"""
    global current_image
    suofangbili=float(input('请输入缩放比例（0.1-5.0）：'))
    current_image = cv2.resize(
        current_image,  # 原图
        (int(current_image.shape[1]*suofangbili),int(current_image.shape[0]*suofangbili)),
        interpolation=cv2.INTER_LINEAR  # 插值方法
    )
    print(f"图像缩放完成，新尺寸: {current_image.shape[1]*suofangbili}x{current_image.shape[0]*suofangbili}")
    return True
def select_roi():
    """选择ROI区域"""
    global current_image
    print("请在图像上拖动鼠标选择ROI区域，按空格确认，按ESC取消")

    roi = cv2.selectROI("选择ROI区域", current_image)
    cv2.destroyWindow("选择ROI区域")
    if roi[2] > 0 and roi[3] > 0:
        x, y, w, h = map(int, roi)
        current_image = current_image[y:y + h, x:x + w]
        print(f"ROI选择完成，新尺寸: {w}x{h}")
        return True
    else:
        print("ROI选择取消")
        return False
def save_image():
    global current_image
    filename=input('请输入保存的文件名（包含扩展名）：')
    succ=cv2.imwrite(filename,current_image)
    if succ:
        print(f"图像已保存为: {filename}")
        return True
    else:
        print("保存失败")
        return False
def batch_processing():
    """批量处理 - 类似扫描全能王的工作流"""
    global current_image
    # 1. 畸变纠正
    print("\n=== 步骤1: 畸变纠正 ===")
    correct()
    display('jibianjiuzhenghou')

    # 2. 对比度增强
    print("\n=== 步骤2: 对比度增强 ===")
    adjust_contrast()
    display('duibiduzengqianghou')

    # 3. 亮度增强
    print("\n=== 步骤3: 亮度增强 ===")
    adjust_brightness()
    display('liangduzengqianghou')

    # 4. 保存结果
    print("\n=== 步骤4: 保存结果 ===")
    save_image()

    print("批量处理完成！")








